package com.duoketech.controller.weixin;

import com.alibaba.fastjson.JSONObject;
import com.duoketech.config.Constant;
import com.duoketech.controller.BaseController;
import com.duoketech.exception.ValidateException;
import com.duoketech.interceptor.WxCartInterceptor;
import com.duoketech.model.activity.Activity;
import com.duoketech.model.custom.Customization;
import com.duoketech.model.member.Member;
import com.duoketech.model.modulepic.ModulePic;
import com.duoketech.service.web.member.MemberService;
import com.duoketech.service.weixin.WxModulePicService;
import com.duoketech.service.weixin.activity.WeiXinActivityService;
import com.duoketech.service.weixin.personal.WxPersonalService;
import com.duoketech.utils.DbUtil;
import com.duoketech.utils.WxMsgTemplateUtils;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Kv;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.List;

public class WeiXinController extends BaseController {

    @Before(WxCartInterceptor.class)
    public void index(){
        setAttr("pics",WxModulePicService.ME.queryModulePicBy(ModulePic.TYPE_ADS_INDEX,6));
    }

    public void ajaxIndex(){
        int limit = 3;
        List<Activity> activityList = WeiXinActivityService.ME.queryLastestActivity(limit);
        Kv kv = Kv.by("activityList",activityList);
        renderObject(kv);
    }

    public void personal(){
        render("private/index.html");
    }

    public void doAddPerson(){
        Customization customization = getModel(Customization.class,"");
        try {
            WxPersonalService.ME.savePrivateOrder(customization);
            renderSuccess("操作成功，请保持电话畅通，稍后我们会有领队联系你");
        } catch (ValidateException e) {
            renderError(e.getMessage());
        }
    }


    @Before(WxCartInterceptor.class)
    public void market(){
        setAttr("pics",WxModulePicService.ME.queryModulePicBy(ModulePic.TYPE_ADS_MARKET,6));
        render("product/product.html");
    }

    @Clear
    public void logout(){
        removerMember();
        redirect("login");
    }

    @Clear
    public void login(){
        render("login.html");
    }





    @Clear
    public void code(){
        String code = getPara("code","");
        String secret=Constant.WX_SECRET;
        String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+Constant.WX_APPID+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String result =HttpKit.get(url);
        JSONObject o = JSONObject.parseObject(result);
        if(o!=null){
            String accessToken = o.getString("access_token");
            String openid = o.getString("openid");
            Member t = MemberService.ME.queryMemberByOpenId(openid);
            if(t==null){
                url = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
                result =HttpKit.get(url);
                JSONObject w = JSONObject.parseObject(result);
                String nickName = w.getString("nickname");
                String sex =w.getString("sex");
                String province =w.getString("province");
                String city =w.getString("city");
                String country =w.getString("country");
                String headimgurl =w.getString("headimgurl");
                Member member = new Member();
                member.set(Member.NICK_NAME,nickName);
                member.set(Member.GENDER,sex);
                member.set(Member.PROVINCE,province);
                member.set(Member.CITY,city);
                member.set(Member.COUNTRY,country);
                member.set(Member.AVATAR,headimgurl);
                member.set(Member.OPEN_ID,openid);
                member.set(Member.STATUS,Member.STATUS_NORMAL);
                Date date = new Date();
                member.set(Member.CREATE_TIME,date);
                member.save();
                int memberSer = member.getInt(Member.ID)+10000;
                member.set(Member.MEMBER_SER,memberSer);
                member.update();
                setMember(member);
                WxMsgTemplateUtils.sendMemberJoinMsg(openid,nickName,memberSer);
//                redirect("/weixin/memberSet?open_id="+openid);
                redirect("/weixin");
            }
            //else if(StringUtils.isEmpty(t.getStr(Member.MOBILE))){
//                setMember(t);
//                redirect("/weixin/memberSet?open_id="+openid);
//            }
            else if(t.getInt(Member.STATUS)==Member.STATUS_LOCKED){
                renderText("当用用户被锁定，无法进行登录操作！！");
            }else{
                setMember(t);
                redirect("/weixin");
            }
        }
    }


    public void memberSet(){
        String openid = getPara("open_id");
        Member t = MemberService.ME.queryMemberByOpenId(openid);
        if(t==null){
        }else{
            setAttr("member",t);
            render("member-set.html");
        }
    }

    public void doUpdateMemberSet(){
        String mobile = getPara("mobile","");
        String password = getPara("password","");
        String confirmPassWord = getPara("confirmPassWord","");
        String code = getPara("code","");
        try {
            MemberService.ME.bindMember(getMemberId(),mobile,password,confirmPassWord,code);
            renderSuccess("绑定成功");
        } catch (ValidateException e) {
            renderError(e.getMessage());
        }
    }

    public void ajaxSendMobileCode(){
//        WxMsgTemplateUtils.sendMobileCodeMsg("oaA0n1D0c-jBdiLXCIhOA1vrV8YE");
//        WxMsgTemplateUtils.sendBookSuccessMsg("oaA0n1D0c-jBdiLXCIhOA1vrV8YE","胡承淞",null);
//        WxMsgTemplateUtils.sendPaySuccessMsg("oaA0n1D0c-jBdiLXCIhOA1vrV8YE","胡承淞",null);
//        WxMsgTemplateUtils.sendMemberJoinMsg("oaA0n1D0c-jBdiLXCIhOA1vrV8YE","胡承淞",null);
//        WxMsgTemplateUtils.sendOrderReadyDeleveryMsg("oaA0n1D0c-jBdiLXCIhOA1vrV8YE","胡承淞",null);
//        WxMsgTemplateUtils.sendOrderUnpayMsg("oaA0n1D0c-jBdiLXCIhOA1vrV8YE","胡承淞",null);
//        WxMsgTemplateUtils.sendOrderCancelMsg("oaA0n1D0c-jBdiLXCIhOA1vrV8YE","胡承淞",null);
//        WxMsgTemplateUtils.sendRoomCheckInMsg("oaA0n1D0c-jBdiLXCIhOA1vrV8YE","胡承淞",null);
        renderSuccess("发送成功，请在微信中检查");
    }


    @Clear
    public void doLogin(){
        String mobile = getPara("mobile","");
        String password = getPara("password","");
        try {
            Member member = MemberService.ME.wxDoLogin(mobile,password);
            setMember(member);
            renderSuccess("登录成功");
        } catch (ValidateException e) {
            renderError(e.getMessage());
        }

    }
}
